package main.java.com.chankudo.thread;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * fork/join 框架
 * 多线程执行可以被拆解的任务，继承 RecursiveAction 的任务
 * 执行该任务时无返回值
 */

public class SimpleRecursiveAction extends RecursiveAction{
    public final static int MaxVlue = 50;
    private int start;
    private int end;

    public SimpleRecursiveAction(int start, int end) {
        this.start = start;
        this. end = end;
    }

    @Override
    protected void compute() {
        if (end - start <= MaxVlue){ //符合条件1：任务不再拆解
            int sleepTime =ThreadLocalRandom.current().nextInt(1000);
            try {
                System.out.println("thread: "+Thread.currentThread().getName()+" will sleep " + sleepTime);
                Thread.currentThread().sleep(sleepTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }else{// 否则 拆解任务
            int mid = (int) ((start+end)/2);
            SimpleRecursiveAction lftRecursiveAction = new SimpleRecursiveAction(start, mid);
            SimpleRecursiveAction rgtRecursiveAction = new SimpleRecursiveAction(mid, end);
            lftRecursiveAction.fork();
            rgtRecursiveAction.fork();
        }
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        SimpleRecursiveAction initTask = new SimpleRecursiveAction(0, 1314);
        forkJoinPool.submit(initTask);
        // 等待任务结束
        try {
            forkJoinPool.awaitTermination(3, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        forkJoinPool.shutdown();
    }
    
}
